package org.xnat.xnatfs.connection;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.bradmcevoy.http.MiltonServlet;

public class XnatContextProvider {
  private static final Logger logger = Logger.getLogger ( XnatContextProvider.class );

  public String getRestURL () {
    debug ();

    String retVal = getServerRoot () + getContextPath () + "/REST";
    logger.debug ( "XNAT REST URL " + retVal );
    return retVal;
  }

  protected HttpServletRequest getRequest () {
    return MiltonServlet.request ();
  }

  private String getServerRoot () {
    int pathStart = getRequestURL ().indexOf ( getRequestURI () );
    return getRequestURL ().substring ( 0, pathStart );
  }

  private String getRequestURL () {
    return getRequest ().getRequestURL ().toString ();
  }

  private String getRequestURI () {
    return getRequest ().getRequestURI ();
  }

  private String getContextPath () {
    return getRequest ().getContextPath ();
  }

  private void debug () {
    logger.debug ( "request.getPathInfo: " + getRequest ().getPathInfo () );
    logger.debug ( "request.getContextPath: " + getRequest ().getContextPath () );
    logger.debug ( "request.getServletPath: " + getRequest ().getServletPath () );
    logger.debug ( "request.getRequestURI: " + getRequest ().getRequestURI () );
    logger.debug ( "request.getRequestURL: " + getRequest ().getRequestURL () );
  }
}
